package hibari.server.operations;

import hibari.client.model.Music;
import hibari.client.model.Week;
import hibari.server.lib.AdminLog;
import hibari.server.lib.FileData;
import hibari.server.lib.MultiPartRequest;
import hibari.server.model.ImageData;

import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Blob;

public class NewWeek extends EditWeek {
    public NewWeek(MultiPartRequest request, HttpServletResponse response) {
        super(request, response);
    }

    @Override
    public void doOperation() {
        Week week = new Week();
        updateWeek(week);

        Music music1 = new Music();
        Music music2 = new Music();

        updateMusic(music1, 1);
        updateMusic(music2, 2);

        getPM().makePersistent(week);
        getPM().makePersistent(music1);
        getPM().makePersistent(music2);

        week.setMusic1(music1.getKey());
        week.setMusic2(music2.getKey());

        music1.setWeekId(week.getKey());
        music2.setWeekId(week.getKey());

        getPM().makePersistent(week);
        getPM().makePersistent(music1);
        getPM().makePersistent(music2);

        getPM().close();

        AdminLog.get(getRequest()).addInfo("New Week has been registered!");
    }

    protected void updateMusic(Music music, int i) {
        music.setTitleInEnglish(getMusicParameter(i, "title_en"));
        music.setTitleInJapanese(getMusicParameter(i, "title_jp"));

        FileData musicFileData = getMusicFileData(i, "image");
        if (musicFileData.isSet()) {
            ImageData imageData = new ImageData();
            imageData.setFilename(musicFileData.getFilename());
            imageData.setData(new Blob(musicFileData.getData()));
            getPM().makePersistent(imageData);
            music.setImageId(imageData.getId());
        }

        music.setCompositionInEnglish(getMusicParameter(i, "composition_en"));
        music.setCompositionInJapanese(getMusicParameter(i, "composition_jp"));

        music.setDescriptionInEnglish(getMusicParameter(i, "description_en"));
        music.setDescriptionInJapanese(getMusicParameter(i, "description_jp"));
        music.setDemoUrl(getMusicParameter(i, "demo_url"));
    }

}
